
import 'dart:async';

import 'package:flutter/services.dart';

class Xfspeech {

  static const MethodChannel _channel =
  const MethodChannel('flutter_xfspeech_plugin');
  static const EventChannel _eventChannel =
  const EventChannel('flutter_xfspeech_plugin_stream');

  static Stream<Map<String, Object>> _onGetResult = _eventChannel
      .receiveBroadcastStream()
      .asBroadcastStream()
      .map<Map<String, Object>>((element) => element.cast<String, Object>());

  StreamController<TransResult>? _receiveStream;
  StreamSubscription<Map<String, Object>>? _subscription;

  static Future<String?> get platformVersion async {
    final String? version = await _channel.invokeMethod('getPlatformVersion');
    return version;
  }


  /// 初始化SDK
  static Future init(
      {required String APP_ID}) async {
    var arguments = Map();
    arguments['APP_ID'] = APP_ID;
    await _channel.invokeMethod('init', arguments);
  }

  /// 开始监听唤醒
  static Future startIvw(
      {required String APP_ID}) async {
    var arguments = Map();
    arguments['APP_ID'] = APP_ID;
    await _channel.invokeMethod('startIvw', arguments);
  }

  /// 取消语音唤醒
  static Future ivwCancel() async {
    await _channel.invokeMethod('ivwCancel', {});
  }

  /// 停止语音唤醒
  static Future ivwStop() async {
    await _channel.invokeMethod('ivwStop', {});
  }

  // 开始语音听写
  ///  APP_ID: 开发 APPID
  ///
  ///  mEngineType: 在线/离线 cloud/local
  static Future startIat(
      {required String APP_ID, required String mEngineType}) async {
    var arguments = Map();
    arguments['APP_ID'] = APP_ID;
    arguments['mEngineType'] = mEngineType;
    await _channel.invokeMethod('startIat', arguments);
  }

  /// 停止语音听写
  static Future iatStop() async {
    await _channel.invokeMethod('iatStop', {});
  }

  /// 获取翻译结果流
  Stream<TransResult> onResult() {
    if (_receiveStream == null) {
      _receiveStream = StreamController();
      _subscription = _onGetResult.listen((Map<String, Object> event) {
        print('event----'+ event.toString());
        Map<String, Object> newEvent = Map<String, Object>.of(event);
        _receiveStream?.add(new TransResult.fromMap(newEvent));
      });
    }
    return _receiveStream!.stream;
  }
}

class TransResult {
  TransResult(
      {required this.transResult,
        required this.result,
        required this.success,
        required this.type
      });
  factory TransResult.fromMap(Map<dynamic, dynamic> map) => new TransResult(
    transResult: map['transResult'],
    result: map['result'],
    success: map['success'],
    type: map['type'],
  );
  final String transResult;
  final String result;
  final bool success;
  final String type;
  @override
  String toString() => 'TransResult: $transResult,$result';
}